﻿using CKS2320.Common;
using CKS2320.Common.Model;
using Org.BouncyCastle.Utilities.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CKS2412.Controller
{
    public class SocketHelper
    {
        private Socket sharedSocket;
        private string IpAddress;
        private IPEndPoint IpPoint;
        private bool isConnecting = false;
        private int currentRetryCount = 0;
        private static object _lock = new object();

        public SocketHelper(string ip, int port)
        {
            bool result = Connect(ip, port);
            if (!result)
            {
                MessageBox.Show("未与主机建立连接");
            }
            //this._ip = ip;
            //this._port = port;
        }

        #region 全局soket连接

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private bool Connect(string ip, int port)
        {
            try
            {
                sharedSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.IpAddress = ip;//ip;
                this.IpPoint = new IPEndPoint(System.Net.IPAddress.Parse(ip), port);
                System.Net.IPAddress IP = System.Net.IPAddress.Parse(IpAddress);
                sharedSocket.Connect(IpPoint);
                return true;
            }
            catch (Exception ex)
            {
                ConnectWithRetry();
                return true;
            }
        }

        public void ConnectWithRetry()
        {
            if (isConnecting) return; // 防止重复连接
            isConnecting = true;
            while (currentRetryCount <= 10)
            {
                try
                {
                    // 每次重试前重置Socket（避免使用失效的Socket）
                    sharedSocket?.Dispose();
                    sharedSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sharedSocket.Connect(IpPoint);
                    currentRetryCount = 0; // 连接成功，重置重试计数器
                    isConnecting = false;
                    return; // 连接成功，退出循环
                }
                catch (SocketException ex)
                {
                    currentRetryCount++;
                    Console.WriteLine($"连接失败（第{currentRetryCount}次重试）: {ex.Message}");

                    if (currentRetryCount > 10)
                    {
                        Console.WriteLine($"重连失败！已达最大重试次数 {10}");
                        isConnecting = false;
                        return;
                    }

                    // 等待重试间隔（阻塞当前线程）
                    Thread.Sleep(3000);
                }
                catch (Exception ex)
                {
                    isConnecting = false;
                    //return;
                }
            }
        }

        /// <summary>
        /// Socket 消息回传
        /// </summary>
        /// <returns></returns>
        public string ReceiveMessage()
        {
            DateTime lastExecutionTime = DateTime.Now;
            string receivedData = "";
            try
            {
                while (true)
                {
                    sharedSocket.ReceiveTimeout = 50000; // 毫秒为单位
                    byte[] msg = new byte[1048576];
                    int recv = sharedSocket.Receive(msg);
                    if (recv > 0)
                    {
                        isConnecting = true;
                        receivedData += System.Text.Encoding.UTF8.GetString(msg, 0, recv);
                    }
                    else
                    {
                        break;
                    }
                    // 处理接收到的命令
                    if (receivedData.EndsWith("\r\n"))
                    {
                        break;
                    }
                    // 判断是否已经过去了10秒
                    if ((System.DateTime.Now - lastExecutionTime).TotalSeconds >= 10)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ConnectWithRetry();
                return ex.Message;
            }
            return receivedData;
        }

        /// <summary>
        /// Socket 发送消息
        /// </summary>
        /// <param name="strmsg">消息</param>
        public void SendVarMessage(string strmsg)
        {
            try
            {
                byte[] buffer = new byte[1024];
                buffer = Encoding.UTF8.GetBytes(strmsg + "\r");
                sharedSocket.Send(buffer);
            }
            catch (Exception ex)
            {
            }
        }

        public string sharedSocketSend(string strmsg)
        {
            lock (_lock)
            {
                SendVarMessage(strmsg);
                return ReceiveMessage();
            }
        }

        #endregion 全局soket连接
    }
}